const Router = require('koa-router')
const router = new Router()

const User = require('../moduls/User') //数据库用户存储模板
const bcrypt = require('bcryptjs') //引入密码加密模块
const tools = require('../../config/tools')//加密工具
const gravatar = require('gravatar')//全球公认头像
const jwt = require('jsonwebtoken')//生成token
const keys = require('../../config/keys')//秘钥
const passport = require('koa-passport')//生成令牌
const validateRegisterInput = require('../../validation/register')//引入注册验证
const validateLoginInput = require('../../validation/login')//引入注册验证

//路由表 .allowedMethods()

router.all('/', async ctx => {
  ctx.body = {msg: 'hello koa'}
})
//用户注册接口 @公开接口
router.post('/user/register', async ctx => {
  const data = await ctx.request.body
  const {errors, isValid} = validateRegisterInput(data)
  //判断注册条件是否通过
  if (!isValid) {
    ctx.status = 400
    ctx.body = errors
    return
  }
  //数据库中查找是否有此邮箱和名字
  const findName = await User.find({account: data.account})
  const findEmail = await User.find({email: data.email})
  if (findName.length > 0 || findEmail.length > 0) {
    const error = {}
    error.account = findName.length > 0 ? '注册账号已存在！' : ''
    error.email = findEmail.length > 0 ? '注册邮箱已存在！' : '';
    let delData = []
    for (let key in error) {
      if (error[key] === '') {
        delData.push(key)
      }
    }
    delData.forEach((item, index) => {
      delete error[delData[index]]
    })
    ctx.status = 400
    ctx.body = error
  } else {
    const avatar = gravatar.url(data.email, {s: '200', r: 'pg', d: 'mm'})
    const newUser = new User({
      account: data.account,
      password: tools.enbcrypt(data.password),
      name: data.name,
      email: data.email,
      ID: data.id,
      phone: data.phone,
      admin: data.admin,
      avatar,
    })
    
    //存储到数据库
    await newUser.save().then(user => {
      ctx.body = user
    })
    ctx.status = 200
    ctx.body = newUser
  }
})
//用户登录接口 @公开接口
router.post('/user/login', async ctx => {
  const data = await ctx.request.body
  const {errors, isValid} = validateLoginInput(data)
  //判断是否通过
  if (!isValid) {
    ctx.status = 400
    ctx.body = errors
    return
  }
  //查询是否有注册
  const findOne = await User.find({account: data.name})
  if (findOne.length == 0) {
    ctx.status = 400
    ctx.body = {account: '用户不存在！'}
  } else {
    //注册过，验证密码
    const user = findOne[0]
    var result = await bcrypt.compare(data.password, user.password)//验证密码
    if (result) {
      //添加登录状态
      let id = {"name": user.name}
      let data = {$set: {"isLogin": true}}
      User.updateOne(id, data, () => {
      })
      //准备返回token
      const payload = {id: user.id, name: user.name}//将用户数据加密到token 存ID即可
      const token = jwt.sign(payload, keys.secretOrkey, {expiresIn: 3600})//隐藏的参数，证书，过期时间
      ctx.status = 200
      ctx.body = {success: true, token: 'Bearer ' + token, avatar: user.avatar} //'Bearer后面一定要有空格
    } else {
      ctx.status = 400
      ctx.body = {password: '密码错误'}
    }
  }
})
//删除用户接口
router.post('/user/del', async (ctx) => {
  const data = await ctx.request.body
  await User.remove(data);
  let flag = await User.find(data)
  if (flag.length > 0) {
    ctx.body = {success: false, messages: '删除失败！'}
  } else {
    ctx.body = {success: true, messages: '删除成功！'}
  }
})
//修改单个用户资料接口
router.post('/user/up', async (ctx) => {
  const data = await ctx.request.body
  await User.updateOne({account: data.account}, {
    $set: {
      ID: data.ID, admin: data.admin,
      email: data.email,
      name: data.name,
      phone: data.phone
    }
  }).then(res => {
    ctx.status = 200
    ctx.body = {
      success: true,
      messages: '修改成功！'
    }
    
  }).catch(err => {
    ctx.status = 400
    ctx.body = {
      success: false,
      messages: '修改失败！'
    }
  })
  
})
//修改密码接口  @私密接口
router.post('/user/upPassword', async (ctx) => {
  const data = await ctx.request.body
  await User.updateOne({account: data.account}, {
    $set: {password: tools.enbcrypt(data.password)}
  }).then(res => {
    ctx.status = 200
    ctx.body = {
      success: true,
      messages: '修改成功！'
    }
  }).catch(err => {
    ctx.status = 400
    ctx.body = {
      success: false,
      messages: '修改失败！'
    }
  })
  
})
//获取单个用户信息
router.post('/user/get', async (ctx) => {
  const data = await ctx.request.body
  let model = await User.find(data)
  let {ID, account, admin, email, name, phone} = model[0]
  if (model.length > 0) {
    ctx.body = {success: true, model: {ID, account, admin, email, name, phone}}
  } else {
    ctx.body = {success: true, messages: '无此用户！'}
  }
})

//用户获取登录信息  @私密接口
router.post('/user/current', passport.authenticate('jwt', {session: false}), async ctx => {
  const data = await ctx.state.user[0]
  ctx.body = data
})
//查询注册用户列表接口
router.get('/userList/query', async ctx => {
  const data = await ctx.request.query
  let findObj = {...{code: 5000}, ...data}
  const users = await User.find(findObj)//获取user数据列表
  let model = users.map(item => {
    return {
      ID: item.ID,
      account: item.account,
      date: item.date,
      email: item.email,
      admin: item.admin,
      name: item.name,
      phone: item.phone
    }
  })
  ctx.status = 200
  ctx.body = {success: true, model: model} //'Bearer后面一定要有空格
})

module.exports = router
